package com.example.demo.controller.ai;

import com.example.demo.util.RestRequestUtil;
import com.example.demo.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

/**
 * @Description:
 * @author: liyuan
 * @data 2020-12-14 16:30
 */
@RestController
@RequestMapping("/")
public class ParamPyTestController {
    @Autowired
    private RestTemplate restTemplate;

    /***
     * 并发测试python性能，测试虚拟机
     * @param number
     * @return 5个请求 "data": "804ms"
     *50是   "data": "8956ms"
     *500 是  "data": "83337ms"
     */
    @Value("${test.rootPath}")
    private String rootPath;
    @Value("${test.projectDir}")
    private String projectDir;
    @Value("${djang.AIUrl}")
    private String djangAIUrl;
    //    @javax.annotation.Resource(name = "simpleThreadPoolTaskExecutor")
    @Autowired
    @Qualifier(value = "simpleThreadPoolTaskExecutor")
    private ThreadPoolTaskExecutor executorService;
    private Logger logger = LoggerFactory.getLogger(ParamPyTestController.class);

    @RequestMapping("forFormAction")
    public ResultVO forFormAction(@RequestParam("number") Integer number, @RequestParam(value = "picture") MultipartFile[] picture) {
        if (number < 1 && picture.length < 1) {
            return ResultVO.error();
        }
        long start = System.currentTimeMillis();
        //不停的请求测试
        for (int j = 0; j < number; j++) {
            for (int i = 0; i < picture.length; i++) {
                String s = dJangoRestServer(picture[i].getResource());
            }
        }
        long end = System.currentTimeMillis();
        return new ResultVO(1000, (end - start) + "ms");
    }

    /***
     * 并发测试：n个线程，一共执行了多少次次的性能测试
     * @param picture
     * @return springboot 线程池使用

     */
    @Deprecated
    @RequestMapping("paramFormAction")
    public ResultVO paramFormAction(
            @RequestParam("allNumber") Integer allNumber,
            @RequestParam(value = "picture") MultipartFile picture) throws InterruptedException, ExecutionException {
        CountDownLatch countDownLatch = new CountDownLatch(allNumber);
        long start = System.currentTimeMillis();
        //不停的请求测试
        for (int i = 0; i < allNumber; i++) {
            executorService.submit(() -> {
                //                picture.name
                String s = dJangoRestServer(picture.getResource());
                logger.info("返回数据:{}", s);
                if (StringUtils.isEmpty(s)) {
                    logger.error("识别错误了");
                }

//                try {
//                    Thread.sleep(10);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println(Thread.currentThread().getName());
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();//不是wait()
        long end = System.currentTimeMillis();
        return new ResultVO(1000, (end - start) + "ms");
    }

    private String dJangoRestServer(Resource resource) {
        HttpHeaders header = RestRequestUtil.getHeader(MediaType.MULTIPART_FORM_DATA);
        header.setBearerAuth("40_LCRv6E6YDiQdh_GNaRq4vSQpVN40o5nBq4yDWwTUkabqLwCxmoR78EPUfwsoEpCy4PS0OYSF-3LYJxSmY_oI8i3I6pjEMGQI6nTtsQLLmiI9-IDPvzMlLNx9kCWTBNPT_BypNdz8EjiT5QfWITVjAHAPAC");
        //上传文件
        MultiValueMap<String, Object> multiValueMap = RestRequestUtil.getEntityByMultiForm();
        multiValueMap.add("image", resource);
        HttpEntity entity = RestRequestUtil.getEntity(multiValueMap, header);
        return restTemplate.postForObject(djangAIUrl, entity, String.class);
    }
}
